from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
import joblib
import pandas as pd
from django.urls import reverse

# 加载训练好的模型
# model = joblib.load('titanic_model.pkl')
# model = joblib.load('titanic_model0111.pkl')

# 加载训练好的模型，使用绝对路径
# model_path = '/Users/jackiezheng/DjangoCourse/django_titanic_02/titanic_app/titanic_model0111.pkl'
# model_path = '/Users/jackiezheng/DjangoCourse/django_titanic_02/titanic_app/titanic_model_20250113_163813.pkl'
# model = joblib.load(model_path)
from django.urls import reverse

model_path = '/Users/jackiezheng/DjangoCourse/django_titanic_02/titanic_app/titanic_model_20250113_210016.pkl'

# 在加载模型时，考虑可能的异常处理
try:
    model = joblib.load(model_path)
except FileNotFoundError:
    print(f"模型文件 {model_path} 未找到，请检查文件路径或确保模型已生成。")
    model = None
except Exception as e:
    model = None
    print(f"加载模型时发生错误：{str(e)}")


from django.shortcuts import render

# 添加首页视图
def home(request):
    return render(request, 'predict_form.html')

def predict_name(reuqest, user_name):
    print("打印反转路由")
    print(reverse("titanic:home"))
    print(reverse("titanic:username", args=["reverseusername"]))
    return HttpResponse(f"user name的值是：{user_name}")


def predict_slug(request, slug):
    return HttpResponse(f"slug是: {slug}")


def predict_path(request, path):
    return HttpResponse(f"path是: {path}")


# def predict_survival(request):
#     if model is None:
#         return JsonResponse({'error': '模型未正确加载，请检查模型文件路径和格式。'}, status=500)
#     if request.method == 'GET' and 'name' in request.GET:
#         name = request.GET['name']
#
#         # 提取相关特征，假设你有一个用户输入的名字来获取相关特征
#         # 这里只是一个简单示范，假设性地提供一些默认特征
#         # passenger_data = {
#         #     'Pclass': 3,  # 船舱等级
#         #     'Sex': 1,  # 性别，1表示男性，0表示女性
#         #     'Age': 22,  # 年龄
#         #     'SibSp': 1,  # 兄弟姐妹或配偶数量
#         #     'Parch': 0,  # 父母或孩子数量
#         #     'Fare': 7.25,  # 票价
#         # }
#
#         passenger_data = {
#             "pclass": 2,
#             "sex": 0,
#             "age": 34,
#             "sibsp": 0,
#             "parch": 0,
#             "fare": 13,
#             "embarked": 2
#         }
#
#         # test_data_df = pd.DataFrame([{
#         #     # "Pclass": 2,
#         #     # "Sex": 0,
#         #     # "Age": 34,
#         #     # "SibSp": 0,
#         #     # "Parch": 0,
#         #     # "Fare": 13,
#         #     # "Embarked": 2
#         #
#         #     "pclass": 2,
#         #     "sex": 0,
#         #     "age": 34,
#         #     "sibsp": 0,
#         #     "parch": 0,
#         #     "fare": 13,
#         #     "embarked": 2
#         # }])
#
#         # 将数据转化为 DataFrame 格式，并保证特征顺序与训练时一致
#         # df = pd.DataFrame([passenger_data])
#
#         # 将数据转为 DataFrame 格式
#         df = pd.DataFrame([passenger_data], columns=["pclass", "sex", "age", "sibsp", "parch", "fare", "embarked"])
#
#         # 预测生存概率
#         # survival_prob = model.predict_proba(df)[:, 1][0]  # 获取生存的概率
#         # print(f"survival_prob {survival_prob}")
#
#         # 预测生存概率
#         try:
#             survival_prob = model.predict_proba(df)[:, 1][0]  # 获取生存概率
#             return JsonResponse({'name': name, 'survival_prob': survival_prob})
#         except Exception as e:
#             print(f"预测时发生错误：{str(e)}")
#             return JsonResponse({'error': '预测失败，请检查输入数据和模型兼容性。'}, status=500)
#
#         # if model is not None:
#         #     try:
#         #         # 预测生存概率
#         #         survival_prob = model.predict_proba(df)[:, 1][0]  # 获取生存的概率
#         #         print(f"survival_prob: {survival_prob}")
#         #
#         #         # 返回 JSON 响应
#         #         return JsonResponse({'name': name, 'survival_prob': survival_prob})
#         #     except Exception as e:
#         #         print(f"预测过程出错: {str(e)}")
#         #         return JsonResponse(
#         #             {'error': 'Prediction failed, please check the input data and model compatibility.'}, status=500)
#         # else:
#         #     return JsonResponse({'error': 'Model not loaded. Please check the model file path.'}, status=500)
#
#         # return render(request, 'predict_form.html', {'name': name, 'survival_prob': survival_prob})
#         # 返回 JSON 响应
#         # return JsonResponse({'name': name, 'survival_prob': survival_prob})
#     # return render(request, 'predict_form.html')
#     return JsonResponse({'error': 'Invalid request'}, status=400)

def predict_survival(request):
    if request.method == 'GET':
        try:
            # 获取前端传递的参数
            pclass = int(request.GET.get('pclass', 0))
            sex = int(request.GET.get('sex', 0))
            age = float(request.GET.get('age', 0))
            sibsp = int(request.GET.get('sibsp', 0))
            parch = int(request.GET.get('parch', 0))
            fare = float(request.GET.get('fare', 0))
            embarked = int(request.GET.get('embarked', 0))

            # 构造数据
            input_data = pd.DataFrame([{
                "pclass": pclass,
                "sex": sex,
                "age": age,
                "sibsp": sibsp,
                "parch": parch,
                "fare": fare,
                "embarked": embarked
            }])

            # 进行预测
            survival_prob = model.predict_proba(input_data)[:, 1][0]  # 生还概率
            return JsonResponse({'survival_prob': survival_prob}, status=200)

        except Exception as e:
            return JsonResponse({'error': f'请求参数无效或预测失败：{str(e)}'}, status=400)

    return JsonResponse({'error': '仅支持 GET 请求'}, status=405)

def chatgpt(request):
    return render(request, 'chatgpt.html')

def predict(request):
    return render(request, 'predict_form.html')
